import React, {Component} from 'react'
import {View, Text, Image, Modal, TouchableOpacity, Slider} from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'
import NavigationService from '../../config/navigate_service'
import styles from '../../config/styles'
import RNFetchBlob from 'react-native-fetch-blob'
import {fsReadPath} from '../../helpers/fsHelper'

var Sound = require('react-native-sound');
//Sound.setCategory('Playback');

class AudioAttachment extends Component {
    static defaultProps = {
        attachment: {}
    }

    constructor(props) {
        super(props)
        this.state = {
            modalVisible: false,
            playing: false,
            voice: null,
            voice_length: 1,
            current_voice_progress: 0
        }
    }

    componentWillUnmount() {
        clearInterval(this.loop_get_time)
        if (this.state.voice != null) {
            this.state.voice.release()            
        }
    }

    closeModal = () => {
        this.setState({modalVisible: false, playing: false}, () => {
            clearInterval(this.loop_get_time)    
            this.state.voice.pause()           
        })
    }

    play = () => {
        if (this.state.playing) {
            this.state.voice.pause();            
            this.setState({playing: false})        
        } else {
                this.setState({playing: true}, () => {
                    this.loop_get_time = setInterval(() => {
                    this.state.voice.getCurrentTime((sec) => {
                        this.setState({current_voice_progress: (sec / this.state.voice_length)})
                    })
                  }, 100)
                  //设置一个轮询使进度条改变
                this.state.voice.play((success) => {
                    if (success) {
                        clearInterval(this.loop_get_time)
                        this.setState({
                            current_voice_progress: 0,
                            playing: false
                        })
                    } else {
                      //this.state.voice.reset();
                    }
                });
            })        
        }
    }

    //打开模态框并加载声音
    openModal = () => {
        this.setState({modalVisible: true}, async () => {
            let filePath = await fsReadPath(this._url())
            //如果Attachment给了awsPath，则直接从s3读取
            this.state.voice = new Sound(filePath, '', (error) => {
                if (error) {
                    console.log(error, 'error')
                    return;
                }
                // loaded successfully
                this.setState({
                    voice_length: this.state.voice.getDuration()
                })
            });
                     
        })
    }

    //进入圆环页面
    goToCircle = () => {
        NavigationService.navigate('circle_slider_audio', {url: this._url()})
    }

    //滑动的时候设置当前秒数
    set_progress = (value) => {
        this.setState({playing: false}, () => {
            this.state.voice.setCurrentTime(this.state.voice_length * value)
        })
    }

    modalTemplate = () => {
        return(
            <Modal
                animationType={'none'}
                visible={this.state.modalVisible}
                transparent={true}
                onRequestClose={() => {}}>

                <TouchableOpacity 
                    style={{flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0,0,0,0.5)', flexDirection: 'row'}} 
                    onPress={() => {this.closeModal()}}>
                    <View style={{flex: 1, backgroundColor: 'white', justifyContent: 'center', flexDirection: 'row', padding: 10}}>
                        <TouchableOpacity
                            style={{flex: 0.1, justifyContent: 'center', alignItems: 'center'}}
                            onPress={this.play}>

                            <View>
                                <Icon name={this.state.playing ? 'pause' : 'play'} size={20}/>
                            </View>
                        </TouchableOpacity>
                        <Slider 
                            style={{flex: 0.9}}
                            value={this.state.current_voice_progress}
                            onValueChange={(value) => {this.set_progress(value)}}/>
                    </View>
            </TouchableOpacity>
        </Modal>
        )
    }

    _url = () => {
        if (this.props.attachment.url.match(/^https:\/\/*/)) {
            return this.props.attachment.url
        } else {
            return App.host + '/api' + this.props.attachment.url
        }
    }

    render () {
        return (
                <View>
                    {this.modalTemplate()}
                    <TouchableOpacity
                        onPress={() => {this.openModal()}}
                        //onPress={this.goToCircle}
                        style={this.props.style}
                    >
                        <View>
                            <Image
                                source={require('../../assets/images/mp3.png')}
                                style={[styles.attachment_view,{marginTop:5}]}
                            />
                        </View>
                    </TouchableOpacity>
                </View>    
            )
    }
}

export default AudioAttachment